﻿#include "bizadd.h"
#include "ui_bizadd.h"

BizAdd::BizAdd(QWidget *parent) :
    ItemAdd(parent),
    ui(new Ui::BizAdd)
{
    ui->setupUi(this);

    table = TD_STOCK;
    info = LST_PROVIDER;

    loadOptions();
}

BizAdd::~BizAdd()
{
    delete ui;
}

void BizAdd::loadOptions()
{
    QStringList optList=getOptions(info);
    if(!optList.isEmpty())
    {
        ui->provider->addItems(optList);
        ui->provider->addItem(OPT_EDIT);
        ui->provider->setCurrentIndex(-1);
    }
    else
        ui->provider->addItem(QStringLiteral("连接错误！"));
}

bool BizAdd::addItem()
{
    QSqlQuery query;
    query.prepare(QString("insert into %1 (date,name,number,provider,remark,status) values (?,?,?,?,?,?)").arg(table));
    query.addBindValue(Env::today);
    query.addBindValue(name);
    query.addBindValue(number);
    query.addBindValue(provider);
    query.addBindValue(remark);
    query.addBindValue(status);
    return query.exec();
}

void BizAdd::on_btn_submit_clicked()
{
    name=ui->name->text().trimmed();
    number=ui->number->text().trimmed();
    provider=ui->provider->currentText();

    if(name.isEmpty() || provider.isEmpty() || number.isEmpty())
    {
        QMessageBox::warning(this,QStringLiteral("不能为空"),QStringLiteral("名称、数量、供货商不能为空！"));
        return;
    }

    remark=ui->remark->text().trimmed();
    if(addItem())
    {
        sendMsg(T_STOCK ,STOCK_NOTICE);
        accept();
    }
    else
        QMessageBox::critical(this,QStringLiteral("异常情况"),QStringLiteral("异常情况，提交失败！"));
}

void BizAdd::reload()
{
    ui->provider->clear();
    loadOptions();
}

void BizAdd::on_provider_currentTextChanged(const QString &text)
{
    if(text == OPT_EDIT)
    {
        OptionEditor editor(this,info);
        editor.exec();
        reload();
    }
}
